/**
 * Created by xiteng on 2017/5/18.
 */
import React, {Component} from 'react';
import {
    StyleSheet,
    View,
    Text,
    TouchableOpacity,
    ListView,
    Dimensions,
    ActivityIndicator
} from 'react-native';
import SearchBox from '../component/SearchBox'
import Constant from '../Contant'
import Toast, {DURATION} from 'react-native-easy-toast';
import {observable} from 'mobx'
import {observer} from 'mobx-react/native'
import RequestUtil from "../util/NetUtil";
import addressMgrStore from "../store/AddrMgrStore";

const SECTIONHEIGHT = 30;
const ROWHEIGHT = 40
var totalheight = [];//每个字母对应的城市和字母的总高度


const {width, height} = Dimensions.get('window');


@observer
export default class CityChooser extends Component {


    static navigationOptions = {
        title: '城市选择',
    };

    @observable loading = true;

    constructor(props) {
        super(props);

        var getSectionData = (dataBlob, sectionID) => {
            return sectionID;
        };
        var getRowData = (dataBlob, sectionID, rowID) => {
            return dataBlob[sectionID][rowID];
        };
        this.state = {
            dataSource: new ListView.DataSource({
                getRowData: getRowData,
                getSectionHeaderData: getSectionData,
                rowHasChanged: (row1, row2) => row1 !== row2,
                sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
            }),
            letters: [],
        };

        that = this;
    }

    _getSortLetters(dataList) {
        let list = [];

        for (let j = 0; j < dataList.length; j++) {
            let sortLetters = dataList[j].sortLetters.toUpperCase();

            let exist = false;
            for (let index = 0; index < list.length; index++) {
                if (list[index] === sortLetters) {
                    exist = true;
                }
                if (exist) {
                    break;
                }
            }
            if (!exist) {
                list.push(sortLetters);
            }
        }
        return list;
    }


    _toLowerCase(str) {
        return str.toLowerCase();
    }


    //条件过滤城市列表
    async _filterCitylist(keyword = '') {
        let key = this._toLowerCase(keyword);
        let ALL_CITY_LIST = await RequestUtil.requestData('common/city/getCities', {});
        this.loading = false;
        let letterList = this._getSortLetters(ALL_CITY_LIST);
        if (keyword && keyword != '') {
            //过滤
            ALL_CITY_LIST = ALL_CITY_LIST.filter((cityJson) => {
                LOG('keyword',keyword);
                LOG('cityJson',JSON.stringify(cityJson));
                let matchName = cityJson.fullName.indexOf(key) != -1;
                let matchSpellName = cityJson.spellName.indexOf(key) != -1;
                let matchSortLetters = cityJson.sortLetters.indexOf(key) != -1;
                return matchName || matchSpellName || matchSortLetters;
            });

        }
        let dataBlob = {};
        ALL_CITY_LIST.map(cityJson => {
            let key = cityJson.sortLetters.toUpperCase();

            if (dataBlob[key]) {
                let subList = dataBlob[key];
                subList.push(cityJson);
            } else {
                let subList = [];
                subList.push(cityJson);
                dataBlob[key] = subList;
            }
        });


        let sectionIDs = Object.keys(dataBlob);
        let rowIDs = sectionIDs.map(sectionID => {
            let thisRow = [];
            let count = dataBlob[sectionID].length;
            for (let ii = 0; ii < count; ii++) {
                thisRow.push(ii);
            }

            var eachheight = SECTIONHEIGHT + ROWHEIGHT * thisRow.length;
            totalheight.push(eachheight);

            return thisRow;
        });
        this.setState({
            letters: letterList,
            dataSource: this.state.dataSource.cloneWithRowsAndSections(dataBlob, sectionIDs, rowIDs)
        });
    }


    componentDidMount() {
        this._filterCitylist();
    }


    _cityNameClick(cityJson) {
        addressMgrStore.setCity(cityJson.fullName) ;
        this.props.navigation.goBack();
    }

    _scrollTo(index, letter) {
        this.refs.toast.close();
        let position = 0;
        for (let i = 0; i < index; i++) {
            position += totalheight[i]
        }
        this._listView.scrollTo({
            y: position
        });
        this.refs.toast.show(letter, DURATION.LENGTH_SHORT);
    }

    _renderRightLetters(letter, index) {
        return (
            <TouchableOpacity
                key={'letter_idx_' + index}
                activeOpacity={0.6}
                onPress={() => {
                    this._scrollTo(index, letter)
                }}>
                <View style={styles.letter}>
                    <Text style={styles.letterText}>{letter}</Text>
                </View>
            </TouchableOpacity>
        );
    }

    _renderListRow(cityJson, rowId) {
        return (
            <TouchableOpacity
                key={'list_item_' + cityJson.id}
                style={styles.rowView}
                onPress={() => {
                    that._cityNameClick(cityJson)
                }}>
                <View style={styles.rowdata}>
                    <Text style={styles.rowdatatext}>{cityJson.fullName}</Text>
                </View>
            </TouchableOpacity>
        )
    }

    _renderListSectionHeader(sectionData, sectionID) {
        return (
            <View style={styles.sectionView}>
                <Text style={styles.sectionText}>
                    {sectionData}
                </Text>
            </View>
        );
    }


    render() {
        if (this.loading) {
            return (
                <View style={{flex: 1, backgroundColor: Constant.GRAYBGCOLOR}}>
                    <View style={styles.center}>
                        <ActivityIndicator/>
                    </View>
                </View>
            );
        }
        return <View style={styles.container}>
            <View style={styles.listContainner}>
                <View style={{marginHorizontal: 10, marginVertical: 5}}>
                    <SearchBox
                        placeholder="输入城市关键字/拼音"
                        textChange={(keyword) => {
                            this._filterCitylist(keyword);
                        }}/>
                </View>
                <ListView
                    ref={listView => this._listView = listView}
                    contentContainerStyle={styles.contentContainer}
                    dataSource={this.state.dataSource}
                    renderRow={this._renderListRow}
                    renderSectionHeader={this._renderListSectionHeader}
                    enableEmptySections={true}
                    initialListSize={500}
                />
                <View style={styles.letters}>
                    {this.state.letters.map((letter, index) => this._renderRightLetters(letter, index))}
                </View>
            </View>
            <Toast
                ref="toast"
                position='top'
                positionValue={200}
                fadeInDuration={750}
                fadeOutDuration={1000}
                opacity={0.8}
            />
        </View>
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'column',
        backgroundColor: '#F4F4F4',
        // paddingTop: Platform.OS === 'ios' ? 20 : 0,  // 处理iOS状态栏
    },
    listContainner: {
        flex: 1,
        marginBottom: 10
    },
    contentContainer: {
        flexDirection: 'row',
        width: width,
        backgroundColor: 'white',
        justifyContent: 'space-around',

        flexWrap: 'wrap',
    },
    letters: {
        position: 'absolute',
        height: height,
        top: 64,
        bottom: 0,
        right: 10,
        backgroundColor: 'transparent',
        justifyContent: 'center',
        alignItems: 'flex-start',
    },
    letter: {
        height: height * 3.3 / 100,
        width: width * 3 / 50,
        justifyContent: 'center',
        alignItems: 'center',
    },
    letterText: {
        textAlign: 'center',
        fontSize: height * 1.1 / 50,
        color: '#4964ef'
    },
    sectionView: {
        paddingTop: 5,
        paddingBottom: 5,
        height: 30,
        paddingLeft: 10,
        width: width,
        backgroundColor: '#F4F4F4',
    },
    sectionText: {
        color: '#4964ef',
        fontWeight: 'bold'
    },
    rowView: {
        height: ROWHEIGHT,
        paddingLeft: 10,
        paddingRight: 10,
        borderBottomColor: '#F4F4F4',
        borderBottomWidth: 0.5,
    },
    rowdata: {
        paddingTop: 10,
        paddingBottom: 2,
        marginLeft: 15
    },
    rowdatatext: {
        color: 'gray',
        width: width,
    },
    center: {
        justifyContent: 'center',
        alignItems: 'center',
        flex: 1
    }
});